package com.my.demo.config;

import com.alibaba.fastjson.JSONObject;
import com.zhenzi.sms.ZhenziSmsClient;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.sound.midi.SoundbankResource;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "register")
@Data
//使用榛子云提供的api发送短信
public class ZhenZi {
  private String apiUrl;
  private String appId;
  private String appSecret;

  private ZhenZi() {

  }

  //发送短信的核心方法
  public JSONObject send_message(String phone) throws Exception {
    JSONObject json = null;
    ZhenziSmsClient client = new ZhenziSmsClient(apiUrl, appId, appSecret);
    Map<String, Object> params = new HashMap<String, Object>();
    params.put("number", phone);
    params.put("templateId", "6985");
    String[] templateParams = new String[2];
    templateParams[0] = create_message();
    templateParams[1] = "5";
    params.put("templateParams", templateParams);
    String result = client.send(params);

    json = JSONObject.parseObject(result);
    json.put("verifyCode", templateParams[0]);
    System.out.println(json);
    return json;
  }

  //随机产生6位的验证码
  public String create_message() {
    String sources = "0123456789"; //如果加上字母，还能生成字母验证码
    Random rand = new Random();
    StringBuffer flag = new StringBuffer();
    for (int j = 0; j < 6; j++) {
      flag.append(sources.charAt(rand.nextInt(9)) + "");
    }
    String message = flag.toString();
    return message;
  }

}
